package com.suncnpap.base.common;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class Ticket {
	
	private static Map<String, List<Object>> ticketMap=new HashMap<String, List<Object>>();
	private static String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	
	public static String getTicket(int length){//length表示生成字符串的长度
	    Random random = new Random();   
	    StringBuffer sb = new StringBuffer();   
	    for (int i = 0; i < length; i++) {   
	        int number = random.nextInt(base.length());   
	        sb.append(base.charAt(number));   
	    }   
	    return sb.toString();   
	}


	//生成token字符串
	public static String getRandom(String userId,String strTicket) { 
	    Random random = new Random();   
	    StringBuffer sb = new StringBuffer();   
	    for (int i = 0; i < 10; i++) {   
	        int number = random.nextInt(base.length());   
	        sb.append(base.charAt(number));   
	    }   
	    System.out.println(sb+"============");
	    List<Object> loginInfo=new ArrayList<Object>();
	    loginInfo.add(userId);
	    loginInfo.add(strTicket);
	    loginInfo.add(new Date().getTime());
	    ticketMap.put(sb.toString(), loginInfo);
	    return sb.toString();   
	 }

	public static Map<String, List<Object>> getTicketMap() {
		return ticketMap;
	}
	
	public static String getgetRandomValue(String ticket){
		List<Object> obj=Ticket.getTicketMap().get(ticket);
		if(obj!=null){
			long nowTime=new Date().getTime();
			long oldTime=(Long)obj.get(1);
			if((nowTime-oldTime)<(5*60*1000)){//有效期 5分钟
				Ticket.getTicketMap().remove(ticket);
				return (String)obj.get(0);
			}
		}
		return "";
	
	}
	
	public static void invalTicket(){
		//删除过期的登录信息  定时清理一天前登录的用户信息
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DAY_OF_YEAR,-1);
//		List<Object> args=new ArrayList<Object>();
//		args.add(calendar.getTime());
		try{
//			loginUserService.deleteByTime(DateUtil.get(calendar.getTime(), "yyyy-mm-dd hh:mm:ss"));
		}catch(Exception e){
			
		}
		//删除过期的验证码
		Iterator<String> keySet=ticketMap.keySet().iterator();
		while (keySet.hasNext()){
			String key=keySet.next();
			List<Object> obj=Ticket.getTicketMap().get(key);
			if(obj!=null){
				long nowTime=new Date().getTime();
				long oldTime=(Long)obj.get(1);
				if((nowTime-oldTime)>=(5*60*1000)){//有效期 5分钟
					Ticket.getTicketMap().remove(key);
				}
			}
		}
	}
}
